package com.jukte.recipe.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.util.Log;

import com.jukte.recipe.db.DataBaseManager;
import com.jukte.recipe.utils.Constants;

public class CheckDataTask extends AsyncTask<Void, Integer, String> {
	private ProgressDialog pd;
	private SharedPreferences prefs;
    private Editor edt;
	
	private String[] tables = new String[]{"categories", "custom_ingredients", "directions",
			"ing_group", "ingredients", "recipe_sub_category_relation",
			"recipes", "sub_categories", "tips"};
	public CheckDataTask(Context ctx, ProgressDialog pd) {
		this.pd = pd;
		prefs = ctx.getSharedPreferences("QUINOA", Context.MODE_PRIVATE);
	}
	
	@Override
	protected void onPreExecute() {
		pd.setMessage("Checking data...");
		if(!pd.isShowing()) pd.show();
	}
	
	@Override
	protected String doInBackground(Void... params) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Constants.WS_PATH + "checkVersion.php");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("version", prefs.getInt("VERSION", 0)+""));
			httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

			HttpResponse response = httpclient.execute(httppost);

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// get the response content as a string
				InputStream instream = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(instream, "UTF-8"));
				String line;
				StringBuilder sb = new StringBuilder("");
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}

				Log.i("XXX", sb.toString());
				
				JSONObject job = new JSONObject(sb.toString());
				if(!job.getBoolean("hasData")){
					return "NO_DATA";
				}else{
					return job.getString("version");
				}
			}
		} catch (UnsupportedEncodingException e1) {
			Log.e("Exception", "" + e1.getMessage());
			return e1.getMessage();
			// e1.printStackTrace();
		} catch (ClientProtocolException e1) {
			Log.e("ClientProtocolException", "" + e1.getMessage());
			return e1.getMessage();
			// e1.printStackTrace();
		} catch (IOException e1) {
			Log.e("IOException", "" + e1.getMessage());
			return e1.getMessage();
			// e1.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return "OK";
	}

	@Override
	protected void onPostExecute(String result) {
		if("NO_DATA".equals(result)){
			pd.dismiss();
			onNoData();
		}else{
			onHasData(result);
		}
	}

	public void onNoData() {}
	public void onHasData(String version) {}
}
